<template>
  <div ref="rightPanel" :class="{ show: show }" class="rightPanel-container">
    <div class="rightPanel-background" />
    <div class="rightPanel">
      <div
        class="rightPanel-items"
        :style="{ transform: show ? 'translateX(-' + buttonLeft + 'px)' : 'translateX(0px)' }"
      >
        <div class="rightPanel-btn" @click="show = !show">
          <el-icon>
            <Close v-if="show" />
            <Setting v-else />
          </el-icon>
        </div>
        <div class="rightPanel-content">
          <slot />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue'
import { Close, Setting } from '@element-plus/icons-vue'

interface Props {
  clickNotClose?: boolean
  buttonTop?: number
}

const props = withDefaults(defineProps<Props>(), {
  clickNotClose: false,
  buttonTop: 250
})

const show = ref(false)
const rightPanel = ref<HTMLElement>()

const buttonLeft = computed(() => {
  return 250
})

const addEventClick = () => {
  window.addEventListener('click', closeSidebar)
}

const closeSidebar = (evt: Event) => {
  const parent = (evt.target as Element)?.closest('.rightPanel')
  if (!parent) {
    show.value = false
    window.removeEventListener('click', closeSidebar)
  }
}

// 监听显示状态
watch(show, (value) => {
  if (value && !props.clickNotClose) {
    addEventClick()
  }
  
  if (value) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = 'auto'
  }
})

onUnmounted(() => {
  window.removeEventListener('click', closeSidebar)
  document.body.style.overflow = 'auto'
})
</script>

<style lang="scss" scoped></style>
